package cn.ctyun.cloudflow.sdk.util;


import org.apache.commons.codec.binary.Hex;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.security.InvalidKeyException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

public class Codec {
    private final static String ALGORITHM_SHA256 = "SHA-256";
    private final static String ALGORITHM_HMAC_SHA256 = "HmacSHA256";

    public static String hexSHA256(String text) throws NoSuchAlgorithmException {
        MessageDigest md = MessageDigest.getInstance(ALGORITHM_SHA256);
        md.update(text.getBytes());
        return Hex.encodeHexString(md.digest());
    }

    public static byte[] HmacSHA256(byte[] data, byte[] key) throws NoSuchAlgorithmException, InvalidKeyException {
        Mac mac = Mac.getInstance(ALGORITHM_HMAC_SHA256);
        mac.init(new SecretKeySpec(key, ALGORITHM_HMAC_SHA256));
        return mac.doFinal(data);
    }
}

